//客户退货js
var orderDetail = JSON.parse(sessionStorage.getItem("serviceProviderorderDetail"));
console.log(orderDetail)
var returnedGoodsall=''
var dataDifferentiation=false//数据区分（新数据旧数据）
var promotionvaluet=""//特价金额
var promotionvaluel=""//立减分摊金额
var usedpoints=""//积分分摊金额
$("#detailAddress").val(0)
window.parent.isIngReturn = false;
//默认不退运费
var is_returnable_freight=true
if(is_returnable_freight==true){
    $(".notui").attr("onclick", "return false;");
    $(".notui").css({"color": "grey"});
}else{
    $(".notui").attr("onclick", "return false;");
    $(".notui").css({"color": "grey"});
    $(".tui").attr("onclick", "return false;");
    $(".tui").css({"color": "grey"});
}
//第三方
$("#receivedame").hide();
if($("#getGoodsType").val()==10){
    var orderDetail = JSON.parse(sessionStorage.getItem("serviceProviderorderDetail"));
    if(orderDetail.addressReceiverPOList!=null){
        $('#received_name').val(orderDetail.addressReceiverPOList[0].receiverName);
        $('#received_telephone').val(orderDetail.addressReceiverPOList[0].mobile);
    }

}
//开票状态判断
setTimeout(function (){
    $('#invoicetype').text(orderDetail.invoiceType);
}, 500);

var yunfie=0

checkRoles();
function checkRoles() {
    if(JSON.parse(decodeURIComponent(web.readCookie("loginData"))).rolesName == null ||JSON.parse(decodeURIComponent(web.readCookie("loginData"))).rolesName == ''){
        if(dataDifferentiation){
            $('#getGoodsAddress').html('');        
        }else{
            $('#getGoodsAddress').html(orderDetail.receiverProvinceName + ' ' + orderDetail.receiverCityName + ' ' + orderDetail.receiverAreaName + ' ' + orderDetail.receiverTownName + '' + orderDetail.receiverDetailAddress);
        }


    } else {
        for(var i = 0; i < JSON.parse(decodeURIComponent(web.readCookie("loginData"))).rolesName.length; i++) {
            console.log(JSON.parse(decodeURIComponent(web.readCookie("loginData"))).rolesName[i].ROLE_NAME)
            if(JSON.parse(decodeURIComponent(web.readCookie("loginData"))).rolesName[i].ROLE_NAME=='门店操作员'){

                $("#getGoType").css({
                    display: "inline"
                });
                $("#getGoodsType").css({
                    display: "none"
                });
                $("#receivedame").hide();
                $("#huohuo").hide();
                $("#huodao").hide();
                $('#getGoodsAddress').html(''+''+''+''+'');
            }else {
                if(dataDifferentiation){
                    $('#getGoodsAddress').html('');                
                }else{
                    $('#getGoodsAddress').html(orderDetail.receiverProvinceName + ' ' + orderDetail.receiverCityName + ' ' + orderDetail.receiverAreaName + ' ' + orderDetail.receiverTownName + '' + orderDetail.receiverDetailAddress);
                }

            }
        }
    }
}


//初始化带入参数
$("#freight").val("0");
/*设置各种金额*/
var Return_goods = 0;//退货商品金额
var Share_freight=0 //退货商品分摊运费
var Share_coupon=0//分摊优惠(进位)
var table;   //table对象
var rejectSomeArray = {};//拒收列表对象
//查询商品信息
productInformation()
function productInformation(){
    $("#datatablerel").hide()
    $.ajax({
        contentType: "application/json;charset=UTF-8",
        url: root.serviceProviderManagement.getReverseDetail,
        cache: false, //禁用缓存
        type: "POST",
        dataType: "json",
        async: false,//优先运行
        data: JSON.stringify({
            orderId:orderDetail.orderId

        }),
        success: function (data) {
            returnedGoodsall=data.data.itemResponseList
            var productInformation=""
            if(data.data.itemResponseList !="" && data.data.itemResponseList!=null){
                var arr=data.data.itemResponseList

                //算出该活动的所有商品小计和优惠值
                let ii =""
                let ruleStret = '<tr><td colspan="11"><div>' +
                    '<span style="float: left;">'+ii+'</span>' +
                    '</div></td></tr>';
                productInformation +=ruleStret;

                $.each(arr,function(k,v){
                        if(v.couldRejectCount==0){
                            productInformation+='<tr class="biaoge1" bgcolor="#a9a9a9">' +
                                '<td class="biaoge1-1"><div onclick="goToGoodsDetail('+v.spuId+')" style="cursor:pointer;"><img style="float: left;width:100px;height:100px;" name="" src="'+v.productPic+'" alt=""><div style="float: left;width:180px;padding-top: 20px;margin-left: 10px;"><div>'+ v.skuCode +'</div><div>'+ v.productName +'</div><div>'+ v.skuInfo +'</div></div></div>' +
                                '<td class="biaoge1-1"><span id="handle_man">'+v.sendGoodWarehouse+'</span></td>' +
                                '<td class="biaoge1-3"><span id="create_time">' + v.salePrice + '元/' + v.unitName + '</span></td>'+
                                '<td class="biaoge1-2"><span id="handle_results">' + v.buyerCount + '' + v.unitName + '</span></td>' +
                                '<td class="biaoge1-3"><span id="create_time">' + v.deliveryCount + '' + v.unitName + '</span></td>'+
                                '<td class="biaoge1-3"><span id="create_time">' + v.couldRejectCount + '' + v.unitName + '</span></td>'+
                                '<td class="biaoge1-3"><span><input type="text" disabled="disabled" class="input-text mr-5" oninput="creatArray('+v.skuCode+',this,\'some\','+0+')" value="" style="width: 100px" placeholder="" id="" name=""><span style="display: none">'+v.skuCode+'</span><span style="display: none">'+v.salePrice+'</span><span style="display: none">'+0+'</span><span style="display: none">'+0+'</span><span style="display: none">'+v.buyerCount+'</span><span style="display: none">'+0+'</span><span style="display: none">'+0+'</span><span style="display: none">'+0+'</span></span>'+ v.unitName+'</td>'+
                                '</tr>';
                        }else {
                            productInformation+='<tr class="biaoge1">' +
                                '<td class="biaoge1-1"><div onclick="goToGoodsDetail('+v.spuId+')" style="cursor:pointer;"><img style="float: left;width:100px;height:100px;" name="" src="'+v.productPic+'" alt=""><div style="float: left;width:180px;padding-top: 20px;margin-left: 10px;"><div>'+ v.skuCode +'</div><div>'+ v.productName +'</div><div>'+ v.skuInfo +'</div></div></div>' +
                                '<td class="biaoge1-1"><span id="handle_man">'+v.sendGoodWarehouse+'</span></td>' +
                                '<td class="biaoge1-3"><span id="create_time">' + v.salePrice + '元/' + v.unitName + '</span></td>'+
                                '<td class="biaoge1-2"><span id="handle_results">' + v.buyerCount + '' + v.unitName + '</span></td>' +
                                '<td class="biaoge1-3"><span id="create_time">' + v.deliveryCount + '' + v.unitName + '</span></td>'+
                                '<td class="biaoge1-3"><span id="create_time">' + v.couldRejectCount + '' + v.unitName + '</span></td>'+
                                '<td class="biaoge1-3"><span><input type="text" class="input-text mr-5" oninput="creatArray('+v.skuCode+',this,\'some\','+0+')" value="" style="width: 100px" placeholder="" id="" name=""><span style="display: none">'+v.skuCode+'</span><span style="display: none">'+v.salePrice+'</span><span style="display: none">'+0+'</span><span style="display: none">'+0+'</span><span style="display: none">'+v.buyerCount+'</span><span style="display: none">'+0+'</span><span style="display: none">'+0+'</span><span style="display: none">'+0+'</span></span>'+ v.unitName+'</td>'+
                                '</tr>';
                        }

                    }
                )


            }
            $("#datatable").find("tbody").empty().append($(productInformation));

        },
    })
}
//全部退货
function returnAll() {
    $("#datatablerel").show()
    $("#datatable").hide()
    $(".jiansuo").val("")
    //商品信息
    orderList()
    function orderList() {
        $.ajax({
            contentType: "application/json;charset=UTF-8",
            url: root.serviceProviderManagement.getReverseDetail,
            cache: false, //禁用缓存
            type: "POST",
            dataType: "json",
            async: false,//优先运行
            data: JSON.stringify({
                orderId:orderDetail.orderId

            }),
            success: function (data) {
                var returnedGoods=""
                if(data.data.itemResponseList !="" && data.data.itemResponseList!=null){
                    var arr=data.data.itemResponseList

                    //算出该活动的所有商品小计和优惠值
                    let ii =""
                    let ruleStret = '<tr><td colspan="11"><div>' +
                        '<span style="float: left;">'+ii+'</span>' +
                        '</div></td></tr>';
                    returnedGoods +=ruleStret;

                    $.each(arr,function(k,v){
                            if(v.couldRejectCount==0){
                                returnedGoods+='<tr class="biaoge1" bgcolor="#a9a9a9">' +
                                    '<td class="biaoge1-1"><div onclick="goToGoodsDetail('+v.spuId+')" style="cursor:pointer;"><img style="float: left;width:100px;height:100px;" name="" src="'+v.productPic+'" alt=""><div style="float: left;width:180px;padding-top: 20px;margin-left: 10px;"><div>'+ v.skuCode +'</div><div>'+ v.productName +'</div><div>'+ v.skuInfo +'</div></div></div>' +
                                    '<td class="biaoge1-1"><span id="handle_man">'+v.sendGoodWarehouse+'</span></td>' +
                                    '<td class="biaoge1-3"><span id="create_time">' + v.salePrice + '元/' + v.unitName + '</span></td>'+
                                    '<td class="biaoge1-2"><span id="handle_results">' + v.buyerCount + '' + v.unitName + '</span></td>' +
                                    '<td class="biaoge1-3"><span id="create_time">' + v.deliveryCount + '' + v.unitName + '</span></td>'+
                                    '<td class="biaoge1-3"><span id="create_time">' + v.couldRejectCount + '' + v.unitName + '</span></td>'+
                                    '<td class="biaoge1-3"><span><input type="text" disabled="disabled" class="input-text mr-5" oninput="creatArray('+v.skuCode+',this,\'all\','+0+')" value="'+v.couldRejectCount+'" style="width: 100px" placeholder="" id="" name=""><span style="display: none">'+v.skuCode+'</span><span style="display: none">'+v.salePrice+'</span><span style="display: none">'+0+'</span><span style="display: none">'+0+'</span><span style="display: none">'+v.buyerCount+'</span><span style="display: none">'+0+'</span><span style="display: none">'+0+'</span><span style="display: none">'+0+'</span></span>'+ v.unitName+'</td>'+
                                    '</tr>';
                            }else {
                                returnedGoods+='<tr class="biaoge1">' +
                                    '<td class="biaoge1-1"><div onclick="goToGoodsDetail('+v.spuId+')" style="cursor:pointer;"><img style="float: left;width:100px;height:100px;" name="" src="'+v.productPic+'" alt=""><div style="float: left;width:180px;padding-top: 20px;margin-left: 10px;"><div>'+ v.skuCode +'</div><div>'+ v.productName +'</div><div>'+ v.skuInfo +'</div></div></div>' +
                                    '<td class="biaoge1-1"><span id="handle_man">'+v.sendGoodWarehouse+'</span></td>' +
                                    '<td class="biaoge1-3"><span id="create_time">' + v.salePrice + '元/' + v.unitName + '</span></td>'+
                                    '<td class="biaoge1-2"><span id="handle_results">' + v.buyerCount + '' + v.unitName + '</span></td>' +
                                    '<td class="biaoge1-3"><span id="create_time">' + v.deliveryCount + '' + v.unitName + '</span></td>'+
                                    '<td class="biaoge1-3"><span id="create_time">' + v.couldRejectCount + '' + v.unitName + '</span></td>'+
                                    '<td class="biaoge1-3"><span><input type="text" class="input-text mr-5" oninput="creatArray('+v.skuCode+',this,\'all\','+0+')" value="'+v.couldRejectCount+'" style="width: 100px" placeholder="" id="" name=""><span style="display: none">'+v.skuCode+'</span><span style="display: none">'+v.salePrice+'</span><span style="display: none">'+0+'</span><span style="display: none">'+0+'</span><span style="display: none">'+v.buyerCount+'</span><span style="display: none">'+0+'</span><span style="display: none">'+0+'</span><span style="display: none">'+0+'</span></span>'+ v.unitName+'</td>'+
                                    '</tr>';
                            }


                        }
                    )


                }
                $("#datatablerel").find("tbody").empty().append($(returnedGoods));

            },
        })


    }
    //运费和扣税置空
    $("#return_freight").html("0")
    isSetReturnFreight = 0;
    $(".notui").attr("onclick", "return false;");
    $(".notui").css({"color": "grey"});
     $(".tui").css({"color": "#1e79e9"});
     $(".tui").attr("onclick", "setReturnFreight(1)");
     $(".tui").css({"opacity": "2.6"});
    yunfie=0
    service(1);

    for(var i = 0; i < returnedGoodsall.length; i++) {
        if(returnedGoodsall[i].couldRejectCount != 0){
            rejectSomeArray[returnedGoodsall[i].skuCode] = {
                productCode: returnedGoodsall[i].skuCode,
                sale_price: returnedGoodsall[i].salePrice,//当前单价
                refundCount: returnedGoodsall[i].couldRejectCount,
                fare:0,//当前运费
                coupon_value:0,//当前优惠价格
                library:returnedGoodsall[i].buyerCount,//当前出库数量
                promotionvalue:0,//当前特价
                activitytype:0,//特价商品
                used_points:0//积分分摊

            }
        }
    }
    var service_fee=$('#service_fee').val()
    var freight=$('#freight').val()
    $('#refund_amount_final').html('0')
    Share_freight=0
    Share_coupon=0
    Return_goods=0
    var reduceAmount = 0;
    var usedpoint=0;
    var Return_goodsCS=$("#Return_goods").text();
    for(var key in rejectSomeArray){
        if(rejectSomeArray[key].refundCount!=0){
            console.log(rejectSomeArray[key].used_points+"积分分摊积分分摊积分分摊积分分摊积分分摊")
        }

        // Return_goods += Number(rejectSomeArray[key].refundCount)*Number(rejectSomeArray[key].sale_price);
        //禁止多次点击全部退货
        Share_freight+=Number(rejectSomeArray[key].fare)*Number(rejectSomeArray[key].refundCount)/Number(rejectSomeArray[key].library);
        Share_coupon+=Number(rejectSomeArray[key].coupon_value)*Number(rejectSomeArray[key].refundCount)/Number(rejectSomeArray[key].library)

        var returnPromotionValue = Number(rejectSomeArray[key].promotionvalue) * Number(rejectSomeArray[key].refundCount)/Number(rejectSomeArray[key].library)
        var used_pointsValue = Number(rejectSomeArray[key].used_points) * Number(rejectSomeArray[key].refundCount)/Number(rejectSomeArray[key].library)
        usedpoint+=used_pointsValue
        // 特价
        if(10 == rejectSomeArray[key].activitytype){
            Return_goods+=Number(rejectSomeArray[key].sale_price)*Number(rejectSomeArray[key].refundCount) - Number(returnPromotionValue)
        }else{
            Return_goods+=Number(rejectSomeArray[key].sale_price)*Number(rejectSomeArray[key].refundCount)
            reduceAmount += returnPromotionValue;
        }
    }
    promotionvaluel=(reduceAmount).toFixed(2)
    usedpoints=(usedpoint).toFixed(2)
    $("#recoupon").html((reduceAmount).toFixed(2))
    $("#integrals").html((usedpoint).toFixed(2))
    if(Return_goods==0){
        $("#Return_goods").html(Return_goods)
    }else{
        $("#Return_goods").html((Return_goods).toFixed(2))
    }

    // 判断是否运费券
    /*if (null != orderDetail.orderCoupon && 20 == orderDetail.orderCoupon.coupon_type) {
        $("#Share_freight").html((Number(Share_freight) - Number(Share_coupon)).toFixed(2))
        $("#Share_coupon").html(0)
    } else {

    }*/
    $("#Share_freight").html((Share_freight).toFixed(2))
    $("#Share_coupon").html((Share_coupon).toFixed(2))

    if ( $("#freight").val() == "0") {
        service(1);
        service(2);
    }
}

var arr = [];
var result = 0;
// 退货数量
function creatArray(skuCode,val,someOrAll,number_decimal) {
    //退运费金额
$("#return_freight").html("0")
    isSetReturnFreight = 0;
    $(".notui").attr("onclick", "return false;");
    $(".notui").css({"color": "grey"});
    yunfie=0
/*-------------------------*/

    var lijian=0//立减分摊
    var promvalue=0
    var librarys=0//购买数量
    var tui=0//退货数量
   var reduceAmount=0
    var usedpoint=0
    var Return_goods = 0;//退货商品金额
    var Share_freight=0 //退货商品分摊运费
    var Share_coupon=0//分摊优惠(进位)
    var numbers = $(val).parent().parent().prev().children().text()
    //只能输入一个小数点
    val.value = val.value.replace(/[^\d.]/g,""); //清除"数字"和"."以外的字符
    val.value = val.value.replace(/^\./g,""); //验证第一个字符是数字
    val.value = val.value.replace(/\.{2,}/g,""); //只保留第一个, 清除多余的
    val.value = val.value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
    var number = numbers.replace(/[^0-9.]/g,"")
    console.log(number)
    // 验证输入的退货数量
    checkInput(number, val,number_decimal)
    if(val.value != "" || someOrAll == "some"){
        // 判断退货数量是否超出实际可退数量
        $.each(returnedGoodsall, function (i, field) {
        });
        var refundCountdq=val.value
        if(val.value==''){
            refundCountdq=0
        }
        rejectSomeArray[val.nextElementSibling.innerHTML] = {
            productCode: val.nextElementSibling.innerHTML,//当前skuid
            sale_price: val.nextElementSibling.nextElementSibling.innerHTML,//当前单价
            refundCount:refundCountdq,//当前输入退货数量
            fare:val.nextElementSibling.nextElementSibling.nextElementSibling.innerHTML,//当前运费
            coupon_value:val.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.innerHTML,//当前优惠价格
            library:val.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.innerHTML,//当前购买数量
            activitytypee:val.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.innerHTML,//商品状态是否是特价
            promotionvalue:val.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.innerHTML,//特价商品金额
            activitytype:val.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.innerHTML,//状态
            used_points:val.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.innerHTML,//积分分摊金额

        }

        var service_fee=$('#service_fee').val()
        var freight=$('#freight').val()
        $('#refund_amount_final').html('0')
        console.log(rejectSomeArray)

        var used_pointss=""
        for(var key in rejectSomeArray){
            if(rejectSomeArray[key].used_points==undefined){
                used_pointss=0
            }else {
                used_pointss=rejectSomeArray[key].used_points
            }
            // Return_goods += Number(rejectSomeArray[key].refundCount)*Number(rejectSomeArray[key].sale_price);
            Share_freight+=Number(rejectSomeArray[key].fare)*Number(rejectSomeArray[key].refundCount)/Number(rejectSomeArray[key].library);
            Share_coupon+=Number(rejectSomeArray[key].coupon_value)*Number(rejectSomeArray[key].refundCount)/Number(rejectSomeArray[key].library)

            var returnPromotionValue = Number(rejectSomeArray[key].promotionvalue) * Number(rejectSomeArray[key].refundCount)/Number(rejectSomeArray[key].library)
            var used_pointsValue = Number(used_pointss) * Number(rejectSomeArray[key].refundCount)/Number(rejectSomeArray[key].library)
            usedpoint+=used_pointsValue
            // 特价
            if(10 == rejectSomeArray[key].activitytype){
                Return_goods+=Number(rejectSomeArray[key].sale_price)*Number(rejectSomeArray[key].refundCount) - Number(returnPromotionValue)
            }else{
                Return_goods+=Number(rejectSomeArray[key].sale_price)*Number(rejectSomeArray[key].refundCount)
                reduceAmount += returnPromotionValue;
            }



        }

        console.log(Return_goods+"正好金额正好金额正好金额！！！！！")


        //计算立减分摊
        var activitytype=val.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.innerHTML//状态
        if(activitytype==30||activitytype==20||activitytype==31){

                promvalue= Number(rejectSomeArray[skuCode].promotionvalue);//promotionvalue
                librarys= Number( rejectSomeArray[skuCode].library);//购买数量
                tui=Number( rejectSomeArray[skuCode].refundCount);//退货数量
                let tuikuan = promvalue/librarys*tui;//单个商品立减分摊

                if (tui>librarys||tui<=0){//小数位购买修改
                var newArr = [];
                var newRejectSomeArray = {};
                for(var key in rejectSomeArray){
                    if (skuCode != rejectSomeArray[key].productCode){//删除单个商品对象重新添加rejectSomeArray
                        newRejectSomeArray[rejectSomeArray[key].productCode]={"productCode":rejectSomeArray[key].productCode,"activitytype":rejectSomeArray[key].activitytype,
                            "activitytypee":rejectSomeArray[key].activitytypee,"coupon_value":rejectSomeArray[key].coupon_value,
                            "fare":rejectSomeArray[key].fare,"library":rejectSomeArray[key].library,
                            "promotionvalue":rejectSomeArray[key].promotionvalue,"refundCount":rejectSomeArray[key].refundCount,
                            "sale_price":rejectSomeArray[key].sale_price
                        }

                    }
                }


                for(let i=0;i<arr.length;i++){
                    if (skuCode != arr[i].skuCode){//删除多个商品立减分摊
                        newArr.push({"skuCode":arr[i].skuCode,"tuikuan":arr[i].tuikuan})
                    }
                }
                arr = newArr;
                rejectSomeArray = newRejectSomeArray;
            }else {
                //存放多个商品立减分摊
                arr.push({"skuCode":skuCode,"tuikuan":tuikuan})
            }
            for(let i=0;i<arr.length;i++){//所有立减分摊金额总和
                lijian= lijian +arr[i].tuikuan;
            }

            result = lijian;

        }else {
            lijian = result;
        }

        promotionvaluel=reduceAmount
        usedpoints=(usedpoint).toFixed(2)
        $("#recoupon").html((reduceAmount).toFixed(2))
        $("#integrals").html((usedpoint).toFixed(2))
        if(Return_goods==0){
            $("#Return_goods").html(Return_goods)
        }else{
            $("#Return_goods").html((Return_goods).toFixed(2))
        }



        /*// 判断是否运费券
        if (null != orderDetail.orderCoupon && 20 == orderDetail.orderCoupon.coupon_type) {
            $("#Share_freight").html((Number(Share_freight) - Number(Share_coupon)).toFixed(2))
            $("#Share_coupon").html(0)
        } else {

        }*/
        $("#Share_freight").html((Share_freight).toFixed(2))
        $("#Share_coupon").html((Share_coupon).toFixed(2))
        if ( $("#freight").val() == "0") {
            service(1);
            service(2);
        }
    }else if(val.value != "" || someOrAll == "all"){
        rejectSomeArray[val.nextElementSibling.innerHTML].refundCount = val.value;
        var refundCountdq=val.value
        if(val.value==''){
            var refundCountdq=0
        }
        console.log(val.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.innerHTML)
        rejectSomeArray[val.nextElementSibling.innerHTML] = {
            productCode: val.nextElementSibling.innerHTML,//当前skuid
            sale_price: val.nextElementSibling.nextElementSibling.innerHTML,//当前单价
            refundCount:refundCountdq,//当前输入退货数量
            fare:val.nextElementSibling.nextElementSibling.nextElementSibling.innerHTML,//当前运费
            coupon_value:val.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.innerHTML,//当前优惠价格
            library:val.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.innerHTML,//当前购买数量
            activitytype:val.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.innerHTML,//商品状态是否是特价
            promotionvalue:val.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.innerHTML,//特价商品金额
            used_points:val.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.innerHTML,//积分分摊金额


        }
        console.log(rejectSomeArray)


        var service_fee=$('#service_fee').val()
        var freight=$('#freight').val()
        var used_pointss=""
        for(var key in rejectSomeArray){
            console.log(rejectSomeArray[key].used_points)
            if(rejectSomeArray[key].used_points==undefined){
                used_pointss=0
            }else {
                used_pointss=rejectSomeArray[key].used_points
            }
            Share_freight+=Number(rejectSomeArray[key].fare)*Number(rejectSomeArray[key].refundCount)/Number(rejectSomeArray[key].library);
            Share_coupon+=Number(rejectSomeArray[key].coupon_value)*Number(rejectSomeArray[key].refundCount)/Number(rejectSomeArray[key].library)
            var returnPromotionValue = Number(rejectSomeArray[key].promotionvalue) * Number(rejectSomeArray[key].refundCount)/Number(rejectSomeArray[key].library)

            var used_pointsValue = Number(used_pointss) * Number(rejectSomeArray[key].refundCount)/Number(rejectSomeArray[key].library)
            usedpoint+=used_pointsValue
            // 特价
            if(10 == rejectSomeArray[key].activitytype){
                Return_goods+=Number(rejectSomeArray[key].sale_price)*Number(rejectSomeArray[key].refundCount) - Number(returnPromotionValue)
            }else{
                Return_goods+=Number(rejectSomeArray[key].sale_price)*Number(rejectSomeArray[key].refundCount)
                reduceAmount += returnPromotionValue;
            }
        }

        var activitytype=val.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.nextElementSibling.innerHTML
        console.log(activitytype)
        if(activitytype==30||activitytype==20||activitytype==31){
            promvalue= Number(rejectSomeArray[skuCode].promotionvalue);
            librarys= Number( rejectSomeArray[skuCode].library);
            tui=Number( rejectSomeArray[skuCode].refundCount);

            let tuikuan = promvalue/librarys*tui;
            if (tui>librarys||tui<=0){//小数位购买修改
                var newArr = [];
                var newRejectSomeArray = {};
                console.log("asjdaksjdas"+rejectSomeArray.length)
                for(var key in rejectSomeArray){
                    if (skuCode != rejectSomeArray[key].productCode){
                        newRejectSomeArray[rejectSomeArray[key].productCode]={"productCode":rejectSomeArray[key].productCode,"activitytype":rejectSomeArray[key].activitytype,
                            "activitytypee":rejectSomeArray[key].activitytypee,"coupon_value":rejectSomeArray[key].coupon_value,
                            "fare":rejectSomeArray[key].fare,"library":rejectSomeArray[key].library,
                            "promotionvalue":rejectSomeArray[key].promotionvalue,"refundCount":rejectSomeArray[key].refundCount,
                            "sale_price":rejectSomeArray[key].sale_price
                        }

                    }
                }

                for(let i=0;i<arr.length;i++){
                    if (skuCode != arr[i].skuCode){
                        newArr.push({"skuCode":arr[i].skuCode,"tuikuan":arr[i].tuikuan})
                    }
                }
                arr = newArr;
                rejectSomeArray = newRejectSomeArray;
            }else {
                arr.push({"skuCode":skuCode,"tuikuan":tuikuan})
            }
            for(let i=0;i<arr.length;i++){
                lijian= lijian +arr[i].tuikuan;
            }

            result = lijian;

        }else {
            lijian = result;
        }



        promotionvaluel=reduceAmount
        usedpoints=(usedpoint).toFixed(2)
        $("#recoupon").html((reduceAmount).toFixed(2))
        $("#integrals").html((usedpoint).toFixed(2))
        if(Return_goods==0){
            $("#Return_goods").html(Return_goods)
        }else{
            $("#Return_goods").html((Return_goods).toFixed(2))
        }



        // 判断是否运费券
       /* if (null != orderDetail.orderCoupon && 20 == orderDetail.orderCoupon.coupon_type) {
            $("#Share_freight").html((Number(Share_freight) - Number(Share_coupon)).toFixed(2))
            $("#Share_coupon").html(0)
        } else {

        }*/
        $("#Share_freight").html((Share_freight).toFixed(2))
        $("#Share_coupon").html((Share_coupon).toFixed(2))
    }

    // 退运费金额
    if(isSetReturnFreight){
        $("#return_freight").html($("#Share_freight").html())
    }

}
//服务费
function service(val) {
    var freight=$('#freight').val() // 运费
    var Return_goods= $("#Return_goods").text() // 退货商品金额
    var Share_freight= $("#Share_freight").text() // 退货商品分摊运费
    var Share_coupon=$("#Share_coupon").text() //退货商品分摊优惠
    var return_freight = $("#return_freight").text(); // 退运费（订单运费）
    var recoupon= $("#recoupon").text(); // 立减分摊
    var integrals= $("#integrals").text(); // 积分分摊金额    
    var total =(Number(Return_goods)+Number(Share_freight)-Number(Share_coupon)-Number(recoupon)-Number(integrals))*0.15 // 服务费 <= 退货商品开票金额 * 15%
    var totals =(Number(Return_goods)-Number(Share_coupon)) // 退货商品实际支付金额
    console.log(total)
    if(val==1){

            //特价金额
            var promotionvaluets=""
            if(promotionvaluet==""){
                promotionvaluets=0
            }else {
                promotionvaluets= promotionvaluet
            }

            
        var refund_amount_final = Number(Return_goods)-Number(freight)-Number(Share_coupon)+Number(return_freight)-promotionvaluel-usedpoints;

            $('#refund_amount_final').html((refund_amount_final).toFixed(2));
            console.log("服务费的应退金额："+refund_amount_final);

    }else{

            //特价金额
            var promotionvaluets=""
            if(promotionvaluet==""){
                promotionvaluets=0
            }else {
                promotionvaluets= promotionvaluet
            }
            var refund_amount_final = Number(Return_goods)-Number(freight)-Number(Share_coupon)+Number(return_freight)-promotionvaluel-usedpoints;

            $('#refund_amount_final').html((refund_amount_final).toFixed(2))
            console.log("运费的应退金额："+refund_amount_final)

    }
}


function round2(number,fractionDigits){  
    with(Math){  
        return round(number*pow(10,fractionDigits))/pow(10,fractionDigits);  
    }  
}  
//限制输入框只能输入两位小数
function clearNoNum(obj) {
    obj.value = obj.value.replace(/[^\d.]/g, ""); //清除“数字”和“.”以外的字符
    obj.value = obj.value.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
    obj.value = obj.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');//只能输入两个小数
    if (obj.value.indexOf(".") < 0 && obj.value != "") {//以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
      obj.value = parseFloat(obj.value);
    }
    if (!obj.value || obj.value == '0' || obj.value == '0.0' || obj.value == '0.00') {
    //   alert('退款金额不能为空');
      return;
    }
    //  正常得话继续调后端接口
  }
function checkInput(number, e,number_decimal) {
    var value = $(e).val();
    var reg = /[^0-9.]/g;
    // 为空
    // if (value == null || value == "") {
    //     showErrorMsg(e, "不能为空，请输入");
    //     $(e).val(0);
    // }
    // 数字和.
    if (reg.test(value) == true) {
        showErrorMsg(e, "格式错误，请重新输入");
        $(e).val(reg.match(value));
        return false;
    }
      //判断小数购买
    if(value!=""){
        if(value.toString().split(".")[1]!=undefined){
            if(value.toString().split(".")[1].length>number_decimal){
          showErrorMsg(e, "不符合该商品的可退范围");
                return false;
      }
        }

    }
    if(number_decimal==0){
        if(value=="0"){
            showErrorMsg(e, "不符合该商品的可退范围");
            return false;

        }
    }else if(number_decimal==1){
        if(value=="0.0"){
            showErrorMsg(e, "不符合该商品的可退范围");
            return false;

        }
    }else if(number_decimal==2){
        if(value=="0.00"){
            showErrorMsg(e, "不符合该商品的可退范围");
            return false;

        }
    }else if(number_decimal==3){
        if(value=="0.000"){
            showErrorMsg(e, "不符合该商品的可退范围");
            return false;

        }
    }
    value = Number(value);
    number = Number(number);
    // 大于购买数量
    console.log(value)
    console.log(number)
    if (value > number) {
        showErrorMsg(e, "退货数量不能大于可退货数量！");
        return false;
        if(value==0){
            $(e).val(number);// 默认数量
        }
        // 为0或者负数
    }


}
function showErrorMsg(e, msg) {
    // 清空非法数据
    $(e).val("");
    $.Huimodalalert(msg, 2000);
}

var originAddress = true;//有没有修改地址 true为原始地址，false为修改后的地址
var isIng = false;

function returnSome() {
    if($("#getGoodsAddress").html()=='' || $("#detailAddress").val()==''){
        $("#alerror").css({
            display: "inline"
        });
        return false;
    }
    if(isIng){
        layer.msg('请求已提交，请勿重复点击！');
        return false;
    }
    isIng = true;
    /*最终退款总金额*/
    console.log(rejectSomeArray)
//  var refund_amount_final = 0;
    var listOrderRefundItems = [];
    for(var key in rejectSomeArray){
        if(rejectSomeArray[key].refundCount!=""){
            listOrderRefundItems.push(rejectSomeArray[key]);
        }
    }

    for(var i=0;i<listOrderRefundItems.length;i++){
        delete listOrderRefundItems[i].activitytype;
        delete listOrderRefundItems[i].activitytypee;
        delete listOrderRefundItems[i].coupon_value;
        delete listOrderRefundItems[i].fare;
        delete listOrderRefundItems[i].library;
        delete listOrderRefundItems[i].promotionvalue;
        delete listOrderRefundItems[i].sale_price;
        delete listOrderRefundItems[i].used_points;
        if(listOrderRefundItems[i].refundCount == ""){
            listOrderRefundItems.splice(i,1);
        }
    }

    console.log(listOrderRefundItems)
    var getgoodsType='';
    var operaterole ='';
    if(JSON.parse(decodeURIComponent(web.readCookie("loginData"))).rolesName == null ||JSON.parse(decodeURIComponent(web.readCookie("loginData"))).rolesName == '') {

            getgoodsType = $("#getGoodsType").val()
        operaterole =20;

    }else {
        for (var i = 0; i < JSON.parse(decodeURIComponent(web.readCookie("loginData"))).rolesName.length; i++) {

            if (JSON.parse(decodeURIComponent(web.readCookie("loginData"))).rolesName[i].ROLE_NAME == '门店操作员') {

                getgoodsType = $("#getGoType").val()
                console.log(getgoodsType)
                operaterole =30;
            }else {

                    getgoodsType = $("#getGoodsType").val()
                    console.log(getgoodsType)
                operaterole =20;
            }
        }

    }
    var provin=""
    var city11 =""
    var area11=""
    var detailaddress=""
    var towns=""
    var provincename =""
    var cityname =""
    var areaname=""
    var townname=""
    var returngoods  =JSON.parse(sessionStorage.getItem("returngoods"))
    $.each(returngoods.data,function(k,s){
        if(orderDetail.parentWarehouseId==s.warehouseId){
            getGoodsAddress=s.provinceName+s.cityName+s.detailAddress
            received_name=s.contactPerson
            received_telephone=s.contactPhone

            provin=s.provinceCode;
            city11 =s.cityCode;
            area11=s.districtCode;
            towns=s.streetCode
            provincename =s.provinceName;
            cityname =s.cityName;
            areaname=s.districtName;
            detailaddress=s.detailAddress;
            townname=s.streetName

        }
    })
    var orderidallall=""
    if($("#getGoodsType").val() == 10){
        if($("#getGoodsType").val()==10&&$("#goods_place").val()==20){
            orderidallall=$("#orderidall").html()
        }else {
            orderidallall=""
        }
        if(originAddress == true){
            var queryData = JSON.stringify({
                orderId: orderDetail.orderId,
                returnReason: parseInt($("#returnReason").val()),//退货原因
                returnDesc: $("#returnRemark").val(),//退货说明
                takeGoodsType:getgoodsType, //取货方式 orderDetail.orderExt.platform==10?'20':
                goodsPlace: $("#goods_place").val(),
                receiverName: $("#received_name").val(),
                receiverTelephone: $("#received_telephone").val(),
                provinceCode: orderDetail.receiverProvince,
                cityCode: orderDetail.receiverCity,
                areaCode: orderDetail.receiverArea,
                townCode: orderDetail.receiverTown,
                provinceName: orderDetail.receiverProvinceName,
                cityName:  orderDetail.receiverCityName,
                areaName:  orderDetail.receiverAreaName,
                townName:  orderDetail.receiverTownName,
                detailAddress: orderDetail.receiverDetailAddress,
                serviceFee: 0,
                shippingFee: parseInt($("#freight").val()),
                returnShippingFlag: isSetReturnFreight,
                refundAmountFinal: $("#refund_amount_final").html(),
                refundRemark: $("#returnMoneyRemark").val(),
                operatorRole: 20,
                operatorId: JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.user_ID,
                operatorName: JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name,
                productList: listOrderRefundItems,
                refundSorce:20
            })
        }else {
            var queryData = JSON.stringify({
                orderId: orderDetail.orderId,
                returnReason: parseInt($("#returnReason").val()),//退货原因
                returnDesc: $("#returnRemark").val(),//退货说明
                takeGoodsType:getgoodsType, //取货方式 orderDetail.orderExt.platform==10?'20':
                goodsPlace: $("#goods_place").val(),
                receiverName: $("#received_name").val(),
                receiverTelephone: $("#received_telephone").val(),
                provinceCode: $("#pin_list1").val(),
                cityCode: $("#pin_list2").val(),
                areaCode: $("#pin_list3").val(),
                townCode: $("#pin_list4").val(),
                provinceName:  $("#pin_list1").find("option:selected").html(),
                cityName:  $("#pin_list2").find("option:selected").html(),
                areaName:  $("#pin_list3").find("option:selected").html(),
                townName:  $("#pin_list4").find("option:selected").html(),
                detailAddress: $("#detailAddress").val(),
                serviceFee: 0,
                shippingFee: parseInt($("#freight").val()),
                returnShippingFlag: isSetReturnFreight,
                refundAmountFinal: $("#refund_amount_final").html(),
                refundRemark: $("#returnMoneyRemark").val(),
                operatorRole: 20,
                operatorId: JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.user_ID,
                operatorName: JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name,
                productList: listOrderRefundItems,
                refundSorce:20

            })
        }
    }else {
        var queryData = JSON.stringify({
            orderId:orderDetail.orderId,
            returnReason: parseInt($("#returnReason").val()),//退货原因
            returnDesc: $("#returnRemark").val(),//退货说明
            takeGoodsType: getgoodsType, //取货方式
            goodsPlace: $("#goods_place").val(),
            receiverName: $("#received_name").val(),
            receiverTelephone: $("#received_telephone").val(),
            provinceCode: provin,
            cityCode: city11,
            areaCode: area11,
            provinceName:  provincename,
            cityName:  cityname,
            areaName:  areaname,
            detailAddress:detailaddress,
            townCode: towns,
            townName:townname,
            serviceFee:0,
            shippingFee:parseInt($("#freight").val()),
            returnShippingFlag: isSetReturnFreight,
            refundAmountFinal:$("#refund_amount_final").html(),
            refundRemark:$("#returnMoneyRemark").val(),
            operatorRole:20,
            operatorId:JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.user_ID,
            operatorName:JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name,
            productList: listOrderRefundItems,
            refundSorce:20
        })
    }
    if(listOrderRefundItems==""){
        layer.msg("校验：退货明细不能为空", {icon: 5, time: 1000});
        isIng = false;
        return false

    }
    if(yunfie==0){
        var curInd = layer.confirm('<span id="status" style="width:200px;height:100px;resize: none;" maxlength="200" >确定不退运费吗？</span>', {closeBtn:false,title:'提示',btn: ['确定', '取消']}, function(index){
            $.ajax({
                contentType: "application/json",
                type: "POST",
                url: root.serviceProviderManagement.refundApply,
                cache: false,  //禁用缓存
                dataType: "json",
                data: queryData,

                success: function (result) {
                    console.log(result);
                    if(result.code == "0"){
                        layer.msg('修改成功', {icon: 6,time:1000});
                        setTimeout( function () {
                            var index =  parent.location.reload();
                            parent.layer.close(index)
                        },1000);
                    }else{
                        isIng = false;
                        layer.msg(result.msg, {icon: 5, time: 1000});
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    isIng = false;
                }
            });
            isIng = false;
            layer.close(curInd);
        },function(){
            isIng = false;
            layer.close(curInd);
        });
    }else {
        $.ajax({
            contentType: "application/json",
            type: "POST",
            url: root.serviceProviderManagement.refundApply,
            cache: false,  //禁用缓存
            dataType: "json",
            data: queryData,

            success: function (result) {
                console.log(result);
                if(result.code == "0"){
                    layer.msg('修改成功', {icon: 6,time:1000});
                    setTimeout( function () {
                        var index =  parent.location.reload();
                        parent.layer.close(index)
                    },1000);
                }else{
                    isIng = false;
                    layer.msg(result.msg, {icon: 5, time: 1000});
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                isIng = false;
            }
        });
           isIng = false;
        layer.close(curInds);		

    }

}

// 商家上门 客户邮寄逻辑
function discount() {
    $("#getGoodsType").change(function(event) {
        var fanx = $(this).find("option:selected");
        if(fanx.val()==10){
            // 商家上门
            var orderDetail = JSON.parse(sessionStorage.getItem("serviceProviderorderDetail"));
            $('#goods_place_box').show();
            if(dataDifferentiation){
                $('#getGoodsAddress').html('');
            }else{
                $('#getGoodsAddress').html(orderDetail.receiverProvinceName+orderDetail.receiverCityName+orderDetail.receiverAreaName+ orderDetail.receiverTownName +orderDetail.receiverDetailAddress);
            }
            $('#modify').show();
            $('#getgoosType').html("取货地址：")
            $('#received_name').attr("disabled",false).val(orderDetail.addressReceiverPOList[0].receiverName);
            $('#received_telephone').attr("disabled",false).val(orderDetail.addressReceiverPOList[0].mobile);
        }else{
            var orderDetail = JSON.parse(sessionStorage.getItem("serviceProviderorderDetail"));
            // 客户邮寄
            $("#Choice_address").hide();
            $("#default_address").show()
            $('#goods_place_box').hide();
            $('#getGoodsAddress').show();
            $('#modify').hide();
            $('#getgoosType').html("邮寄地址：")

            var returngoods  =JSON.parse(sessionStorage.getItem("returngoods"))
            console.log(returngoods)
            var getGoodsAddress=""//取货地址
            var received_name=""//联系人
            var received_telephone=""//联系人电话号
            $.each(returngoods.data,function(k,s){
                if(orderDetail.parentWarehouseId==s.warehouseId){
                    getGoodsAddress=s.provinceName+s.cityName+s.detailAddress
                    received_name=s.contactPerson
                    received_telephone=s.contactPhone
                }
            })
            //取货地址
            $('#getGoodsAddress').html(getGoodsAddress);
            //联系人
            $('#received_name').attr("disabled",true).val(received_name);

            //联系人电话号
            $('#received_telephone').attr("disabled",true).val(received_telephone);


        }
    });
}
// 点击修改地址

function modifydata(val) {

    if(val==1){
        $("#default_address").hide()
        $("#Choice_address").show()

        $("#detailAddress").val(orderDetail.receiverDetailAddress)
        discountdata(123)
        $("#pin_list1").val(orderDetail.receiverProvince);
        setTimeout( function () {
            discountdata(1)
            $("#pin_list2").val(orderDetail.receiverCity);
        },100);
        setTimeout( function () {
            discountdata(2)
            $("#pin_list3").val(orderDetail.receiverArea);
        },200);
        setTimeout( function () {
            discountdata(3)
            $("#pin_list4").val(orderDetail.receiverTown);
        },300);
    }else {
        $("#default_address").show()
        $("#Choice_address").hide()
    }
}

// 点击修改地址 add by milu
function modifyAddress(val) {
    $("#alerror").css({
        display: "none"
    });
    $("#arrtfh").css({
        display: "none"
    });
    if (val == 1) { // 打开修改列表
        $("#default_address").hide();
        $("#Choice_address").show();
        if(JSON.parse(decodeURIComponent(web.readCookie("loginData"))).rolesName == null ||JSON.parse(decodeURIComponent(web.readCookie("loginData"))).rolesName == '') {

            if(dataDifferentiation==true){
                $("#detailAddress").val(orderDetail.receiverProvinceName+orderDetail.receiverCityName+orderDetail.receiverAreaName+orderDetail.receiverTownName+orderDetail.receiverDetailAddress);
                //历史数据
            }else {
                $("#detailAddress").val(orderDetail.receiverDetailAddress);
            }
        }else {
            for (var i = 0; i < JSON.parse(decodeURIComponent(web.readCookie("loginData"))).rolesName.length; i++) {
                if (JSON.parse(decodeURIComponent(web.readCookie("loginData"))).rolesName[i].ROLE_NAME == '门店操作员') {
                    $("#detailAddress").val('')
                }else {
                    if(dataDifferentiation==true){
                        $("#detailAddress").val(orderDetail.receiverProvinceName+orderDetail.receiverCityName+orderDetail.receiverAreaName+orderDetail.receiverTownName+orderDetail.receiverDetailAddress);
                        //历史数据
                    }else {
                        $("#detailAddress").val(orderDetail.receiverDetailAddress);
                    }
                }

            }

        }
        // 初始化选择列表
        queryAddress("pin_list0")
    } else if (val == 2) { // 取消修改
        $("#default_address").show();
        $("#Choice_address").hide();
    } else if (val == 3) { // 保存修改
        if($("#pin_list1").find("option:selected").text()=="请选择"&&$("#pin_list2").find("option:selected").text()=="请选择"&&$("#pin_list3").find("option:selected").text()=="请选择"&&$("#pin_list4").find("option:selected").text()=="请选择"){
            $.Huimodalalert("请选择取货地址", 2000);
            return false
        }
        $('#getGoodsAddress').html($("#pin_list1").find("option:selected").text()+' '
            +$("#pin_list2").find("option:selected").text()+' '
            +$("#pin_list3").find("option:selected").text()+' '
            +$("#pin_list4").find("option:selected").text()+' '+
            $("#detailAddress").val());

        $("#default_address").show();
        $("#Choice_address").hide();
        originAddress = false;
    } else {
        $.Huimodalalert("修改异常，请稍后再试", 2000);
        return;
    }
}
// 地址联动  add by milu
function queryAddress(targetId) {
    var parentCode = ""; // 上级地址ID
    var nextTarget = ""; // 下级下拉列表ID
    var selectedOption = ""; // 选中项

    if ("pin_list0" == targetId) { // 省
        parentCode = "";
        nextTarget = "pin_list1";
        if (originAddress == true) {
            selectedOption = orderDetail.receiverProvince
        } else {
            selectedOption = $("#pin_list1").val();
        }
        console.log(selectedOption)
    } else if ("pin_list1" == targetId) { // 市
        parentCode = $("#pin_list1").val();
        nextTarget = "pin_list2";
        if (originAddress == true) {
            selectedOption = orderDetail.receiverCity
        } else {
            selectedOption = $("#pin_list2").val();
        }
    } else if ("pin_list2" == targetId) { // 县区
        parentCode = $("#pin_list2").val();
        nextTarget = "pin_list3";
        if (originAddress == true) {
            selectedOption = orderDetail.receiverArea
        } else {
            selectedOption = $("#pin_list3").val();
        }
    } else if ("pin_list3" == targetId) { // 城镇
        parentCode = $("#pin_list3").val();
        nextTarget = "pin_list4";
        if (originAddress == true) {
            selectedOption = orderDetail.receiverTown
        } else {
            selectedOption = $("#pin_list4").val();
        }
    }else {
        $.Huimodalalert("选择地址有误", 2000);
        return;
    }

    var user_data = {
        parentCode: parentCode
    };
    var succCallBack = function (data, status, response) {
        if (data.errorCode == "0") {
            var addressList = data.list;
            if (addressList == '') {
                var cer = '<option value=""></option>';
                $("#" + nextTarget).html(cer);
            } else {
                var cer = "";

                if (dataDifferentiation==true ) {
                    console.log(originAddress)
                    //旧数据
                    if(originAddress==true){
                        if ("pin_list0" == targetId) {
                            cer += '<option value="" selected>请选择</option>'
                            for (var i = 0; i < addressList.length; i++) {
                                cer += '<option value="' + addressList[i].code + '">' + addressList[i].name + '</option>'
                            }
                            $("#pin_list1").html(cer);
                            $("#pin_list2").html('<option value="" selected>请选择</option>');
                            $("#pin_list3").html('<option value="" selected>请选择</option>');
                            $("#pin_list4").html('<option value="" selected>请选择</option>');
                        }else if("pin_list1" == targetId){
                            cer += '<option value="" selected>请选择</option>'
                            for (var i = 0; i < addressList.length; i++) {
                                cer += '<option value="' + addressList[i].code + '">' + addressList[i].name + '</option>'
                            }
                            $("#pin_list2").html(cer);
                            $("#pin_list3").html('<option value="" selected>请选择</option>');
                            $("#pin_list4").html('<option value="" selected>请选择</option>');
                        }else if("pin_list2" == targetId){
                            cer += '<option value="" selected>请选择</option>'
                            for (var i = 0; i < addressList.length; i++) {
                                cer += '<option value="' + addressList[i].code + '">' + addressList[i].name + '</option>'
                            }
                            $("#pin_list3").html(cer);
                            $("#pin_list4").html('<option value="" selected>请选择</option>');
                        }else if("pin_list3" == targetId){
                            cer += '<option value="" selected>请选择</option>'
                            for (var i = 0; i < addressList.length; i++) {
                                cer += '<option ' +
                                    'value="' + addressList[i].code + '">' + addressList[i].name + '</option>'
                            }
                            $("#pin_list4").html(cer);
                        }
                    }else {
                        for (var i = 0; i < addressList.length; i++) {
                            if (selectedOption == addressList[i].code) {
                                cer += '<option value="' + addressList[i].code + '" selected>' + addressList[i].name + '</option>'
                            } else {
                                cer += '<option value="' + addressList[i].code + '">' + addressList[i].name + '</option>'
                            }
                        }
                        $("#" + nextTarget).html(cer);
                        if(nextTarget != "pin_list4"){
                            queryAddress(nextTarget);
                        }
                    }


                }else {
                    for (var i = 0; i < addressList.length; i++) {
                        if (selectedOption == addressList[i].code) {
                            cer += '<option value="' + addressList[i].code + '" selected>' + addressList[i].name + '</option>'
                        } else {
                            cer += '<option value="' + addressList[i].code + '">' + addressList[i].name + '</option>'
                        }
                    }
                    $("#" + nextTarget).html(cer);
                    if(nextTarget != "pin_list4"){
                        queryAddress(nextTarget);
                    }
                }
            }
        }
        // 查询子级地址信息
       /* if(nextTarget != "pin_list4"){
            queryAddress(nextTarget);
        }*/
    };
    web.doAjax(root.orderInter.order_return_address_new, 'post', user_data, succCallBack);

    if (targetId == "pin_list1") {
        $("#" + targetId + " option").each(function(){//遍历所有option
            var text = $(this).text();
            var select = $(this).select();
            console.log(select[0].selected);
            if(select[0].selected){
                if (text == "北京" || text == "上海" || text == "天津" || text == "重庆" || text == "台湾" || text == "香港" || text == "澳门" || text == "钓鱼岛") {
                    $("#pin_list4").hide();
                } else {
                    $("#pin_list4").show();
                }

            }

        });
    }

}
//添加地址
function discountdata (val) {
    if(val==123){
        //初始化 省
        var special=$('#pin_list1').val()
        var user_data = {
            level: '101',
            // memberId:'10258',
        }
        var succCallBack = function (data, status, response) {
            console.log(data)
            if(data.errorCode=="1"){
                var tab_data=data.list;
                if(tab_data==''){
                    cer+='<option value=""></option>'
                    $("#pin_list1").html(cer);
                }else{
                    var cer=""
                    for(var i=0; i<tab_data.length; i++){
                        cer+='<option value="'+tab_data[i].address_id+'">'+tab_data[i].name+'</option>'
                    }
                    $("#pin_list1").html(cer);
                }
            }
        };
        web.doAjax(root.orderInter.order_return_address,'post',user_data, succCallBack);
    }else if(val==1){
        //市
        var special=$('#pin_list1').val()
        var user_data = {
            level: '102',
            // memberId:'10258',
            addressIdStr:special
        }
        var succCallBack = function (data, status, response) {
            console.log(data)
            if(data.errorCode=="1"){
                var tab_data=data.list;
                if(tab_data==''){
                    cer+='<option value=""></option>'
                    $("#pin_list2").html(cer);
                }else{
                    var cer=""
                    for(var i=0; i<tab_data.length; i++){
                        cer+='<option value="'+tab_data[i].address_id+'">'+tab_data[i].name+'</option>'
                    }
                    $("#pin_list2").html(cer);
                    $("#pin_list2").val(orderDetail.receiverCity);
                    //选择完省出现市 去记载 区 县
                    discountdata(2)
                    setTimeout( function () {
                        discountdata(3)
                    },100);
                }
            }
        };
        web.doAjax(root.orderInter.order_return_address,'post',user_data, succCallBack);
    }else if(val==2){
        //区
        var special=$('#pin_list2').val()
        var user_data = {
            level: '103',
            // memberId:'10258',
            addressIdStr:special
        }
        var succCallBack = function (data, status, response) {
            console.log(data)
            if(data.errorCode=="1"){
                var tab_data=data.list;
                if(tab_data==''){
                    cer+='<option value=""></option>'
                    $("#pin_list3").html(cer);
                }else{
                    var cer=""
                    for(var i=0; i<tab_data.length; i++){
                        cer+='<option value="'+tab_data[i].address_id+'">'+tab_data[i].name+'</option>'
                    }
                    $("#pin_list3").html(cer);
                    $("#pin_list3").val(orderDetail.receiverArea);
                    //选择完市出现区 去记载  县
                    discountdata(3)
                }
            }
        };
        web.doAjax(root.orderInter.order_return_address,'post',user_data, succCallBack);
    }else if(val==3){
        //县
        var special=$('#pin_list3').val()
        var user_data = {
            level: '104',
            // memberId:'10258',
            addressIdStr:special
        }
        var succCallBack = function (data, status, response) {
            if(data.errorCode=="1"){
                var tab_data=data.list;
                if(tab_data==''){
                    cer+='<option value=""></option>'
                    $("#pin_list4").html(cer);
                }else{
                    var cer=""
                    for(var i=0; i<tab_data.length; i++){
                        cer+='<option value="'+tab_data[i].address_id+'">'+tab_data[i].name+'</option>'
                    }
                    $("#pin_list4").html(cer);
                    if(orderDetail.receiverTown != 0){
                        $("#pin_list4").val(orderDetail.receiverTown);
                    }
                }
            }
        };
        web.doAjax(root.orderInter.order_return_address,'post',user_data, succCallBack);
    }
}

//formdata上传图片公用方法
//触发事件
function addBtn(cen) {
    $("#filesUp").trigger('click');
}
var proofList = [];//初始化图片数组
var formData = new FormData();
// 提交上传图片
function getupfilerul(e){
    console.log(formData)
    $.ajax({
        url: root.inter.imgUpload,
        cache: false,  //禁用缓存
        type: "POST",
        // 告诉jQuery不要去处理发送的数据
        processData : false,
        // 告诉jQuery不要去设置Content-Type请求头
        contentType : false,
        data: formData,
        success: function (data) {
            if(data.errorCode!=0){
                $("#addImgs").hide();
                layer.msg("上传成功", {icon: 6, time: 1000});
                for(var i=0;i<data.length;i++){
                    proofList.push(data[i].fullPath);
                }
                console.log(proofList)
            } else {
                layer.msg(data.errorInfo, {icon: 5, time: 1000});
            }
            console.log(data)
        }
    })
}
// 上传图片返现
function putDataToPage(e) {
    // console.log($("#intro").val())
    if(e.target.files.length >20 ){
        layer.msg("最多添加20张图片", {icon: 6, time: 1000});

        return false;
    }

    for(var i = 0; i < e.target.files.length; i++) {
        var file = e.target.files.item(i);
        if(!(/^image\/.*$/i.test(file.type))) {
            continue; //不是图片 就跳出这一次循环
        }
        //实例化FileReader API
        var freader = new FileReader();
        freader.readAsDataURL(file);
        freader.onload = function (e) {
            /*
                        $(".ceshi").append("<div><img class='myImg' width='50' height='50' style='margin-left: 10px' src='"+e.target.result+"'/></div>");
            */
            $(".ceshi").append("<div><img  class='myImg' onclick=picShow('查看图片','../../../html/goods/picShow.html','"+e.target.result+"','500','300','110') height='30' src='"+e.target.result+"'></div>");
        }
    }
    for(var j=0;j<$("#filesUp")[0].files.length;j++){
        formData.append('file', $("#filesUp")[0].files[j]);
    }
    console.log(formData)
    $.ajax({
        url: root.inter.imgUpload,
        cache: false,  //禁用缓存
        type: "POST",
        // 告诉jQuery不要去处理发送的数据
        processData : false,
        // 告诉jQuery不要去设置Content-Type请求头
        contentType : false,
        data: formData,
        success: function (data) {
            if(data.errorCode!=0){
                $("#addImgs").hide();
                layer.msg("上传成功", {icon: 6, time: 1000});
                for(var i=0;i<data.length;i++){
                    proofList.push(data[i].fullPath);
                }
                console.log(proofList)
            } else {
                layer.msg(data.errorInfo, {icon: 5, time: 1000});
            }
            console.log(data)
        }
    })

    $("#addPicBtn").hide();
    $("#deletBtn").show();
    $("#addImgs").show();
}
//图片放大
function picShow(title, url, imgUrl) {
    window.event ? window.event.cancelBubble = true : e.stopPropagation();
    sessionStorage.setItem("imgUrl", imgUrl);
    layer_show(title, url, "800", "500");
}

//删除图片
function deleteFiles() {
    formData = new FormData();
    $("#addImgs").hide();//隐藏上传按钮
    $(".ceshi").empty();
    $("#addPicBtn").show();
    $("#deletBtn").hide();
    proofList = [];
    /*清空input file文件*/
    var file = document.getElementById("filesUp");
    // for IE, Opera, Safari, Chrome
    if (file.outerHTML) {
        file.outerHTML = file.outerHTML;
    } else { // FF(包括3.5)
        file.value = "";
    }
}
/*跳至商品详情*/
function goToGoodsDetail(spuId) {
    sessionStorage.setItem("spuId", spuId);
    var index = layer.open({
        type: 2,
        title: "Code详情",
        content: "../../goods/goods-sku.html"
    });
    layer.full(index);
}

/*设置是否退运费*/
var isSetReturnFreight = 0; // 0-不退运费；1-退运费
function setReturnFreight(flag) {
    var freight = $('#freight').val() // 运费
    var Return_goods = $("#Return_goods").text() // 退货商品金额
    var Share_coupon = $("#Share_coupon").text() //退货商品分摊优惠
    var return_freight = 0; // 退运费（订单运费）

    if (flag == 1) {
        console.log($("#Share_freight").html())
        return_freight = $("#Share_freight").html();
        $("#return_freight").html(return_freight);
        isSetReturnFreight = 1;
        $(".tui").attr("onclick", "return false;");
        $(".tui").css({"color": "grey"});
        $(".notui").css({"color": "#1e79e9"});
        $(".notui").attr("onclick", "setReturnFreight(2)");
        $(".notui").css({"opacity": "2.6"});
        yunfie=1
    } else {
        $("#return_freight").html(return_freight)
        isSetReturnFreight = 0;
        $(".notui").attr("onclick", "return false;");
        $(".notui").css({"color": "grey"});
        $(".tui").css({"color": "#1e79e9"});
        $(".tui").attr("onclick", "setReturnFreight(1)");
        $(".tui").css({"opacity": "2.6"});
        yunfie=0
    }
    //特价金额
    var promotionvaluets=""
    if(promotionvaluet==""){
        promotionvaluets=0
    }else {
        promotionvaluets= promotionvaluet
    }
    var refund_amount_final = Number(Return_goods) -  Number(freight) - Number(Share_coupon) + Number(return_freight)-promotionvaluel-usedpoints;

    $('#refund_amount_final').html((refund_amount_final).toFixed(2))
}
//关联订单号
function relationOrder() {
    $("#relationOrdertable").find("tbody").html("")
    $.ajax({
        type: "POST",
        url: root.orderInter.queryReturnLinkOrder,
        cache: false,  //禁用缓存F
        dataType: "json",
        data:{
            "customerId": orderDetail.orderBase.customer_id,// 客户id
        },
        success: function (result) {
            var commodityInformation=""
            var datas=result.data
            var hierarchy=0
            if(datas!="" && datas!=null){
                $("#relationOrder").modal("show")
                $.each(datas,function(k,v){
                    hierarchy++;
                        var orderStatus =""
                        if(v.orderStatus==30){
                            orderStatus="待配货"
                        }else if(v.orderStatus==40){
                            orderStatus="待出库"
                        }if(v.orderStatus==50){
                            orderStatus="待发货"
                        }if(v.orderStatus==60){
                            orderStatus="待收货"
                        }
                        var isReturn=""
                        if(v.isReturn==1){
                            isReturn="否"
                        }else {
                            isReturn="是"
                        }
                    var detailAddress=v.provinceName+v.cityName+v.areaName+v.townName+v.detailAddress
                    var detailAddress2=v.provinceName+v.cityName+v.areaName+v.detailAddress
                        if($("#orderidall").html()!=""){
                            if($("#orderidall").html()==v.orderId){
                                commodityInformation+='<tr class="commodityInformations" >' +
                                    '<td class="biaoge1-1"><input class="radio" type="radio" name="relations" value="'+v.orderId+'"  checked="checked"><span >'+hierarchy+'</span></td>' +
                                    '<td class="biaoge1-1"><span >'+v.orderId+'</span></td>' +
                                    '<td class="biaoge1-2"><span >' + orderStatus + '</span></td>' +
                                    '<td class="biaoge1-3"><span >' + isReturn + '</span></td>'+
                                    '<td class="biaoge1-3"><span class="detailAddresk">' + detailAddress + '</span></td>'+
                                    '<td  style="display: none"><span class="biaoge1-6">' + detailAddress2 + '</span></td>'+
                                    '</tr>';
                            }else {
                                commodityInformation+='<tr class="commodityInformations" >' +
                                    '<td class="biaoge1-1"><input class="radio" type="radio" name="relations" value="'+v.orderId+'" ><span >'+hierarchy+'</span></td>' +
                                    '<td class="biaoge1-1"><span >'+v.orderId+'</span></td>' +
                                    '<td class="biaoge1-2"><span >' + orderStatus + '</span></td>' +
                                    '<td class="biaoge1-3"><span >' + isReturn + '</span></td>'+
                                    '<td class="biaoge1-3"><span class="detailAddresk">' + detailAddress + '</span></td>'+
                                    '<td  style="display: none"><span class="biaoge1-6">' + detailAddress2 + '</span></td>'+
                                    '</tr>';
                            }

                        }else {
                            commodityInformation+='<tr class="commodityInformations" >' +
                                '<td class="biaoge1-1"><input class="radio" type="radio" name="relations" value="'+v.orderId+'" ><span >'+hierarchy+'</span></td>' +
                                '<td class="biaoge1-1"><span >'+v.orderId+'</span></td>' +
                                '<td class="biaoge1-2"><span >' + orderStatus + '</span></td>' +
                                '<td class="biaoge1-3"><span >' + isReturn + '</span></td>'+
                                '<td class="biaoge1-3"><span class="detailAddresk">' + detailAddress + '</span></td>'+
                                '<td  style="display: none"><span class="biaoge1-6">' + detailAddress2 + '</span></td>'+
                                '</tr>';
                        }

                    }
                )

                $("#relationOrdertable").find("tbody").html($(commodityInformation));

            }else {
                $("#relationOrder").modal("hide")
                $.Huimodalalert('没有可关联的订单请更换取货方式',2000);
            }

        }
    });
}
//关联订单号确定
function relationOrderdetermine() {
    if($("input[name='relations']:checked").val()==undefined){
        $.Huimodalalert('请关联下次送货订单号',2000);
    }else {
        var getGoodsAddress=$("#getGoodsAddress").html().replace(/\s*/g,"")
        var relationss= $("input[name='relations']:checked").parent().parent().find(".detailAddresk")
        var relationall= $(relationss).html().replace(/\s*/g,"")
        if(relationall!=getGoodsAddress){
            var cu = layer.confirm('<span>当前关联订单收货地址同退货订单收货地址不同确定要关联么？</span>', {title:'提示',btn: ['确认', '取消']}, function(index){
                $("#relationOrder").modal("hide")
                $("#orderidall").html($("input[name='relations']:checked").val())
                layer.close(cu);
            },function(){
                layer.close(cu);

            });
        }else {
            $("#relationOrder").modal("hide")
            $("#orderidall").html($("input[name='relations']:checked").val())
        }

    }
}
//关联订单号取消
function relationOrdercancel() {
    $("#relationOrder").modal("hide")
}

/*//判断是否展示下次送货订单号
exhibition()
function exhibition() {
    if($("#getGoodsType").val()==10&&$("#goods_place").val()==20){

        $("#relationOrders").css({
            display: "inline-block"
        });
    }else {
        $("#relationOrders").css({
            display: "none"
        });
    }
}*/

//检索
function retrievaldatas(obj) {
    if($("#datatable").css("display")=="none"){
        setTimeout(function(){//因为是即时查询，需要用setTimeout进行延迟，让值写入到input内，再读取
            var storeId = document.getElementById('datatablerel');//获取table的id标识
            var rowsLength = storeId.rows.length;//表格总共有多少行
            var key = obj.value;//获取输入框的值
            var searchCol = 0;//要搜索的哪一列，这里是第一列，从0开始数起
            var numsall1=0

            for(var i=1;i<rowsLength;i++){//按表的行数进行循环，本例第一行是标题，所以i=1，从第二行开始筛选（从0数起）
                var searchTextall=""
                var searchText=$($(storeId.rows[i].cells[searchCol].children).children()[1]).find("div")
                for (var m=0;m<searchText.length;m++) {
                    searchTextall+=$($(searchText)[m]).html().trim()
                }
                if(searchTextall!=undefined){
                if(searchTextall.match(key)){//用match函数进行筛选，如果input的值，即变量 key的值为空，返回的是ture，
                    numsall1++;
                    storeId.rows[i].style.display='';//显示行操作，
                }else{
                    storeId.rows[i].style.display='none';//隐藏行操作
                }}
            }
            if(numsall1==0){
                $.Huimodalalert('没有检索到数据',2000);
            }
        },200);//200为延时时间
    }else {
        setTimeout(function(){//因为是即时查询，需要用setTimeout进行延迟，让值写入到input内，再读取
            var storeId = document.getElementById('datatable');//获取table的id标识
            var rowsLength = storeId.rows.length;//表格总共有多少行
            var key = obj.value;//获取输入框的值
            var searchCol = 0;//要搜索的哪一列，这里是第一列，从0开始数起
            var numsall=0
            for(var i=1;i<rowsLength;i++){//按表的行数进行循环，本例第一行是标题，所以i=1，从第二行开始筛选（从0数起）
                var searchTextall=""
                var searchText=$($(storeId.rows[i].cells[searchCol].children).children()[1]).find("div")
                for (var m=0;m<searchText.length;m++) {
                    searchTextall+=$($(searchText)[m]).html().trim()
                }
                if(searchTextall!=undefined){
                    if(searchTextall.match(key)){//用match函数进行筛选，如果input的值，即变量 key的值为空，返回的是ture，
                        storeId.rows[i].style.display='';//显示行操作，
                        numsall++;
                    }else{
                        storeId.rows[i].style.display='none';//隐藏行操作
                    }
                }



            }
          if(numsall==0){
              $.Huimodalalert('没有检索到数据',2000);
          }
        },200);//200为延时时间
    }


}